package day5.client.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.internal.StringUtil;

import java.util.Arrays;
import java.util.List;

public class ChannelInitHandler extends ChannelInitializer<SocketChannel> {

    public ChannelInitHandler() {
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast(new ByteToMessageCodec<ByteBuf>() {
            @Override
            protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
                out.writeBytes(msg);
            }

            @Override
            protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
                int index = in.readableBytes();
                byte[] bytes = ByteBufUtil.getBytes(in.readBytes(index));
                out.add(bytes);
            }
        });
        ch.pipeline().addLast(new SimpleChannelInboundHandler<byte[]>() {

            @Override
            protected void channelRead0(ChannelHandlerContext ctx, byte[] msg) throws Exception {
                System.out.println(Arrays.toString(msg));
            }
        });
    }
}
